import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/features/Home.vue'
import Login from '../views/user/Login.vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { ElMessageBox } from 'element-plus'

// vuex
import { useStore } from 'vuex'

import { useRouter } from 'vue-router'

const routes = [
  {
    path: '/',
    name: 'Home',
    meta: {
      title: '主页'
    },
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '商城系统登录'
    },
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    meta: {
      title: '注册'
    },
    component: () => import('../views/user/Register.vue')
  },
  {
    path: '/category',
    name: 'Category',
    meta: {
      title: '分类'
    },
    component: () => import('../views/features/Category.vue')
  },
  {
    path: '/details',
    name: 'Details',
    meta: {
      title: '详情页'
    },
    component: () => import('../views/details/Detail.vue')
  },
  {
    path: '/manage',
    name: 'Manage',
    meta: {
      title: '管理'
    },
    component: () => import('../views/features/Manage.vue'),
    beforeEnter: (to, from, next) => {
      const store = useStore();
      if(store.state.user.userInfo.manager == 1){
        // 管理员 可以走
        next();
      }else{
        ElMessageBox.alert('您没有此权限,管理员可进行操作', '温馨提示', {
          confirmButtonText: 'OK',
        })
        const current = router.currentRoute.value.fullPath;
        next(current)
      }
    }
  },
  {
    path: '/my-info',
    name: 'Info',
    meta: {
      title: '个人信息'
    },
    component: () => import('../views/user/Info.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      title: '购物车'
    },
    component: () => import('../views/cart/Cart.vue'),
    beforeEnter: (to, from, next) => {
      const store = useStore();
      const router = useRouter();
      if(!store.state.user.token){
        // 未登录
        ElMessageBox.confirm(
          '进入购物车需要先登录,是否帮您跳转至登录界面?',
          'Warning',
          {
            confirmButtonText: 'OK',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            next('/login')
          })
          .catch(() => {
            // 跳到本页面 相当于没跳
            const current = router.currentRoute.value.fullPath;
            next(current)
          })
      }else{
        next();
      }
      
    }
  },
  {
    path: '/order',
    name: 'Order',
    meta: {
      title: '订单中心'
    },
    component: () => import('../views/cart/Order.vue')
  }
]


const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局导航守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? to.meta.title : 'vite + vue3';
  // 页面渲染成功之后，展示进度条（实际效果：Mac的Chrome就是在页面顶部有条2px左右的进度条）
  NProgress.start()
  next();
})

// 页面加载成功之后，关闭进度条
router.afterEach(to => {
  NProgress.done()
})

export default router